<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use think\Db;
use think\Request;

class Pageants extends Common {
    /**
     * @var mixed
     */
    public $params = null;
    /**
     * @param Request $request
     */
    public function __construct(Request $request = null) {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }


    public function config()
    {
        $enter = Db::name('task')->where(['name'=>'pageants', 'sex_limit'=>$this->member['sex'] == '女'?1:2])->value('is_hidden');
        $enter = $enter == 0 ? 1 : 0;
        return $this->pass(compact('enter'));
    }
    /**
     * @param $returnArray
     * @return mixed
     */
    public function current($returnArray = false) {
        $data = Db::name('act_pageants_config')
            ->where(['delete_time' => 0])
            ->where('enroll_time', '<= time', time())
            ->where('end_time', '>= time', time())
            ->field('id,name,description,enroll_time,start_time,end_time')
            ->find();
        if (!$data) {
            exit(json_encode(['code' => 400, 'msg' => '活动配置异常']));
        }
        $data['description'] = preg_replace('/(<img\s+[^>]*\bsrc=")\//i', '$1' . 'http://'.getenv('APP_URL') . '/', $data['description']);

        $hasJoin = Db::name('act_pageants_user')
            ->master()
            ->where(['user_id' => $this->member['id'], 'config_id' => $data['id'], 'state' => 1])
            ->find();
        $data['joined'] = $hasJoin ? true : false;
        return $returnArray ? $data : $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function enroll() {
        $data = $this->current(true);

        $timenow = time();
        if ($timenow < strtotime($data['enroll_time'])) {
            return $this->miss('报名未开始');
        }
        if ($timenow > strtotime($data['end_time'])) {
            return $this->miss('活动已结束');
        }

        if ($data['joined']) {
            return $this->miss('已报名,无需重复报名');
        }

        if ($this->member['sex'] != '女') {
            return $this->miss('仅支持女性报名');
        }

        if (!$this->member['real_avatar']) {
            return $this->miss('需真人头像才可报名');
        }

        $hasJoin = Db::name('act_pageants_user')
            ->master()
            ->where(['user_id' => $this->member['id'], 'config_id' => $data['id']])
            ->find();
        if ($hasJoin['state'] == -1) return $this->miss('报名失败');

        $res = Db::name('act_pageants_user')->insert([
            'user_id'     => $this->member['id'],
            'config_id'   => $data['id'],
            'state'       => 1,
            'create_time' => $timenow,
        ]);
        if ($res) {
            return $this->pass('报名成功');
        }
        return $this->miss('报名失败,请重试');
    }

    /**
     * @return mixed
     */
    public function currentUser() {
        $order    = $this->params['order'] ?? 0;
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $keyword    = $this->params['keyword'] ?? '';

        $data = $this->current(true);

        $orders = [
            'scoring_count desc, update_time desc',
            'scoring_count desc, update_time desc',
            'scoring_count asc, update_time desc ',
            // 'case when score_avg=0 then 1 else 0 end, score_avg asc, update_time desc ',
            'create_time desc',
            'rand()',
        ];
        if (!isset($orders[$order])) {
            $order = 0;
        }

        $where = ['a.config_id' => $data['id'], 'a.state' => 1, 'u.delete_time' => 0];
        if ($keyword) {
            $where['u.id|u.name'] = ['like', '%'.$keyword.'%'];
        }

        $user = Db::name('act_pageants_user')
            ->alias('a')
            ->join('user u', 'a.user_id=u.id')
            ->where($where)
            ->field('a.user_id,a.score_avg,a.scoring_count,u.name,u.head_portrait,u.age,u.sex')
            ->orderRaw($orders[$order])
            ->page($page)
            ->limit($pagesize)
        // ->fetchSql(true)
            ->select();
        // var_dump($user);exit;
        if (sizeof($user)) {
            $scoreTo = Db::name('act_pageants_scoring')
                ->where(['config_id' => $data['id'], 'user_id' => $this->member['id']])
                ->column('score', 'touser_id');

            foreach ($user as &$value) {
                $value['score_avg'] = $value['scoring_count'] . '.0';
                $value['score'] = $scoreTo[$value['user_id']] ?? '未评分';
            }
        }

        return $this->pass($user);
    }

    /**
     * @return mixed
     */
    public function scoring() {
        // $this->member['id'] = 8;
        $touser_id = $this->params['touser_id'] ?? 0;
        $score     = floatval($this->params['score'] ?? 0);
        $data      = $this->current(true);

        if ($this->member['sex'] != '男') {
            return $this->miss('仅限男用户可打分');
        }

        if ($this->member['id'] == $touser_id) {
            return $this->miss('不能给自己打分');
        }

        $user = Db::name('act_pageants_user')
            ->where(['config_id' => $data['id'], 'user_id' => $touser_id, 'state' => 1])
            ->find();
        if (!$user) {
            return $this->miss('数据异常');
        }

        $scoreTo = Db::name('act_pageants_scoring')
            ->master()
            ->where(['config_id' => $data['id'], 'user_id' => $this->member['id'], 'touser_id' => $touser_id])
            ->find();

        if ($scoreTo) {
            return $this->miss('您已给对方打过分了~');
        }

        $legalData = [2, 4, 6, 8, 10];
        if (!in_array($score, $legalData)) {
            return $this->miss('数据不合法');
        }

        $scores = Db::name('act_pageants_scoring')->where([
            'config_id' => $data['id'],
            'touser_id' => $touser_id,
        ])->column('score');
        // 计算平均分
        $score_avg = (array_sum($scores) + $score) / (sizeof($scores) + 1);

        $timenow = time();
        Db::startTrans();
        try {
            Db::name('act_pageants_scoring')->insert([
                'config_id' => $data['id'],
                'user_id'   => $this->member['id'],
                'touser_id' => $touser_id,
                'score'     => $score,
                'time'      => $timenow,
            ]);
            Db::name('act_pageants_user')->where(['id' => $user['id']])->update([
                'scoring_count' => Db::raw('scoring_count+1'),
                'score_avg'     => $score_avg,
                'update_time'   => $timenow,
            ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->miss('打分失败,请重试');
        }
        return $this->pass('打分成功');
    }

    /**
     * @return mixed
     */
    public function before() {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $data = Db::name('act_pageants_config')
            ->where('end_time', '<= time', time())
            ->where(['delete_time' => 0])
            ->field('id,name,enroll_time,start_time,end_time')
            ->order('id desc')
            ->select();

        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function beforeUser() {
        $id       = $this->params['id'] ?? 0;
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $data = Db::name('act_pageants_config')->find($id);

        $order = '';
        $user  = Db::name('act_pageants_user')
            ->alias('a')
            ->join('user u', 'a.user_id=u.id')
            ->where(['a.config_id' => $data['id'], 'a.state' => 1, 'u.delete_time' => 0])
            ->field('a.user_id,a.score_avg,a.scoring_count,u.name,u.head_portrait,u.age,u.sex')
            ->order('a.scoring_count desc, a.update_time desc')
            ->page($page)
            ->limit($pagesize)
            ->select();

        if (sizeof($user)) {
            $scoreTo = Db::name('act_pageants_scoring')
                ->where(['config_id' => $data['id'], 'user_id' => $this->member['id']])
                ->column('score', 'touser_id');

            foreach ($user as &$value) {
                // $value['score'] = $scoreTo[$value['user_id']] ?? '未评分';
                $value['score_avg'] = number_format($value['scoring_count'], 1);
                $value['score'] = '未评分';
            }
        }

        return $this->pass($user);
    }
    public function info()
    {
        $id       = $this->params['id'] ?? 0;
        $user_id       = $this->params['user_id'] ?? 0;

        $where = ['config_id'=>$id, 'user_id'=>$user_id,'delete_time'=>0, 'state'=>1];
        $field = 'delete_time,reason,audit_time';
        if ($user_id == $this->member['id']) {
            unset($where['state']);
            $field = 'delete_time';
        }
        $data = Db::name('act_pageants_user')->where($where)->field($field, true)->find();
        if (!$data) return $this->miss('获取详情失败');
        $data['un_share'] = $data['state'] != 1;

        // 排名
        $data['index'] = 0;
        if ($user_id == $this->member['id']) {
            $user['name'] = $this->member['name'];
            $user['head_portrait'] = $this->member['head_portrait'];
            $user['age'] = $this->member['age'];
            $user['sex'] = $this->member['sex'];
        } else {
            $user = Db::name('user')->where(['id'=>$user_id])->field('name,head_portrait,age,sex')->find();

            $score = Db::name('act_pageants_scoring')
                ->where(['config_id' => $id, 'user_id' => $this->member['id'], 'touser_id'=>$user_id])
                ->value('score');
            $data['score'] = $score ?: '未评分';
        }

        $data['create_time']  = date('Y-m-d H:i', $data['create_time']);
        $data['update_time']  = date('Y-m-d H:i', $data['update_time']);
        $data['user'] = $user;

        return $this->pass($data);
    }
    public function myscoring()
    {
        $id       = $this->params['id'] ?? 3;
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $where = [];
        if ($id) {
            $where['config_id'] = $id;
        }
        $data = Db::name('act_pageants_scoring')
                    ->alias('a')
                    ->join('user u', 'a.touser_id=u.id')
                    ->field('a.config_id,a.touser_id,a.score,a.time,u.head_portrait,u.name,u.sex,u.age')
                    ->where($where)
                    ->page($page)
                    ->limit($pagesize)
                    ->order('a.id desc')
                    ->select();

        foreach ($data as &$value) {
            $value['time'] = date('Y-m-d H:i', $value['time']);
        }
        return $this->pass($data);
    }
}